//
//  ViewController.m
//  RunLoopObserver
//
//  Created by LeeJay on 16/4/22.
//  Copyright © 2016年 LeeJay. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    [self timer];
    [self observer];
}

- (void)observer {
    
    // 创建observer
    
    // 第一个参数用于分配该observer对象的内存空间
    // 第二个参数用以设置该observer监听什么状态
    // 第三个参数用于标识该observer是在第一次进入runloop时执行还是每次进入runloop处理时均执行
    // 第四个参数用于设置该observer的优先级,一般为0
    // 第五个参数用于设置该observer的回调函数
    
    // 回调函数里第一个参数是observer对象
    // 回调函数里第二个参数是observer的运行状态
    CFRunLoopObserverRef observer = CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(), kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
        NSLog(@"----监听到RunLoop状态发生改变---%zd", activity);
    });
    
    // 添加观察者：监听RunLoop的状态
    CFRunLoopAddObserver(CFRunLoopGetCurrent(), observer, kCFRunLoopDefaultMode);
    
    // 释放Observer
    CFRelease(observer);
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    
    NSLog(@"点击");
    
}

- (void)timer {
    
    NSTimer *timer = [NSTimer timerWithTimeInterval:2.0 target:self selector:@selector(run) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    
}

- (void)run {
    NSLog(@"----run");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
